<script setup>
import { reqGetCouponList, reqGetUserIPAddress } from '@/api/index.js'
import {
  reqChangeUserStatus,
  reqDeductUser,
  reqGetUser,
  reqGetUsers,
  reqRechargeUser,
  reqEditUser,
  requserBalances,
  updateUserRechargeStatus
} from '@/api/user/index.js'
import UserItem from '@/components/UserItem.vue'
import { showDialog, showNotify, showToast } from 'vant'
import { onMounted, ref, watch } from 'vue'
const tableData = ref([])
const searchValue = ref('')
const couponList = ref([])
const users = ref([])
const isShowDialog = ref(false)
const currentUserId = ref(0)
const type = ref('0')
const count = ref('')
const showType = ref(false)
const showCoupon = ref(false)
const selectType = ref('赠送金币')
const selectCoupon = ref('')
const page = ref(1)
const lastPage = ref(1)
const loading = ref(false)
const refreshing = ref(false)
const showDetail = ref(false)
const currentUser = ref({})
const showIP = ref(false)
const BlanaceDetail = ref(false)
const htmlStr = ref('')
const vipType = ref('')
const typeList = [
  { value: '', text: '全部' },
  { value: 1, text: '普通用户' },
  { value: 2, text: '主播' },
  { value: 3, text: '推广员' }
]
const userParams = ref({})
const showEdit = ref(false)
const ztsNum = ref('')
const userId = ref('')
const djyPage = ref(1)

onMounted(() => {
  refreshing.value = true
  getUsers()
  getCouponList()
})

const getUsers = async () => {
  try {
    const result = await reqGetUsers({
      id: searchValue.value,
      page: page.value,
      type: vipType.value
    })
    if (result.code === 200) {
      result.data.data.forEach(item => {
        item.zxSta = item.status
      });
      if (page.value === 1) {
        users.value = result.data.data
      } else {
        users.value = users.value.concat(result.data.data)
      }
      console.log(result.data.data)
      page.value++
      lastPage.value = result.data.last_page
    }

  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

const onRefresh = () => {
  page.value = 1
  lastPage.value = 1
  refreshing.value = true
  getUsers()
}

watch(searchValue, () => {
  if (!searchValue.value.trim()) {
    refreshing.value = true
    onRefresh()
  }
})

const getCouponList = async () => {
  try {
    const result = await reqGetCouponList()
    if (result.code === 200) {
      couponList.value = result.data.map((item) => {
        return {
          id: item.id,
          name: item.name + ' ' + item.remark
        }
      })
    }
  } catch (e) {
    console.log(e)
  }
}

const onSearch = () => {
  onRefresh()
}

const zxChange = async ({ id, status }) => {
  const user = users.value.find((item) => item.id === id)
  console.log('用户注销')
  try {
    const result = await reqChangeUserStatus(id, { status: status ? 1 : 0 })
    if (result.code === 200) {
      showNotify({
        type: 'success',
        message: '修改成功'
      })
      user.status = status ? 1 : 0
    } else {
      throw new Error()
    }
  } catch (e) {
    showNotify({
      type: 'danger',
      message: '操作失败'
    })
  }
}
const onChangeStatus = async ({ id, status }) => {
  const user = users.value.find((item) => item.id === id)
  console.log('用户注销')
  try {
    const result = await reqChangeUserStatus(id, { status: status ? 1 : 0 })
    if (result.code === 200) {
      showNotify({
        type: 'success',
        message: '修改成功'
      })
      user.status = status ? 1 : 0
    } else {
      throw new Error()
    }
  } catch (e) {
    showNotify({
      type: 'danger',
      message: '操作失败'
    })
  }
}
const rechargeStatus = async ({ id, status }) => {
  console.log('允许充值')
  const user = users.value.find((item) => item.id === id)

  try {
    const result = await updateUserRechargeStatus({user_id:id,  status: status ? 1 : 0 })
    if (result.code === 200) {
      showNotify({
        type: 'success',
        message: '修改成功'
      })
      user.is_recharge = status ? 1 : 0
    } else {
      throw new Error()
    }
  } catch (e) {
    showNotify({
      type: 'danger',
      message: '操作失败'
    })
  }
}

const showControl = (id) => {
  currentUserId.value = id
  isShowDialog.value = true
  type.value = '0'
  count.value = ''
  selectType.value = '赠送金币'
  selectCoupon.value = ''
}

const actions = ref([])

watch(
  type,
  (newVal) => {
    if (newVal === '0') {
      actions.value = [
        { name: '赠送金币', type: 1 },
        { name: '代充金币', type: 2 },
        { name: '优惠卷', type: 3 },
        { name: '钻石', type: 4 },
        { name: '反悔卡', type: 5 },
        { name: '无限免抽卡', type: 6 },
        { name: '赠送宝箱', type: 7 },
        { name: '幸运码', type: 8 },
        { name: '积分', type: 9 },
        { name: '创业币', type: 10 },
        { name: '水晶', type: 11 },
      ]
    } else {
      actions.value = [
        { name: '金币', type: 1 },
        { name: '钻石', type: 4 },
        { name: '幸运码', type: 8 },
        { name: '水晶', type:11 }
        // { name: '无限免抽卡', type: 6 },
      ]
    }
    selectType.value = actions.value[0].name
    if (newVal === '1' && couponList.value.length) {
      selectCoupon.value = couponList.value[0].name
    }
  },
  {
    immediate: true
  }
)

const onSelect = (item) => {
  selectType.value = item.name

  if (item.name === '优惠卷' && couponList.value.length) {
    selectCoupon.value = couponList.value[0].name
  }
}

const onSubmit = () => {
  const type = actions.value.find((item) => item.name === selectType.value).type

  const data = {
    type,
    user_id: currentUserId.value,
    value: count.value
  }

  if (type === 3) {
    couponList.value.some((item) => {
      if (item.name === selectCoupon.value) {
        data.coupon_id = item.id
        return true
      }
      return false
    })
  } else if (type === 5) {
    data.back_card_id = 1
  }

  showConfirmDialog(data)
}

const showConfirmDialog = (data) => {
  const typeStr = type.value === '0' ? '充值' : '扣除'
  const message = `确定要给${currentUserId.value}${typeStr}${count.value}个${selectType.value}嘛？`
  showDialog({
    title: '提示',
    message: message,
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    let result
    if (type.value === '0') {
      // 充值
      result = await reqRechargeUser(data.user_id, data)
    } else {
      result = await reqDeductUser(data.user_id, data)
    }
    if (result.code === 200) {
      showToast({ type: 'success', message: result.msg })
    } else {
      showToast({ type: 'fail', message: result.msg })
    }
  })
}

const onLoadMore = () => {
  if (page.value >= lastPage.value) return
  getUsers()
}

const showDetailDialog = (item) => {
  showDetail.value = true
  currentUser.value = item
}


const paginationChage = (e) => {
  console.log(e)
  djyPage.value = e
  reqye()

}



const onBlanaceDetail = async (item) => {
  userId.value = item.id
  reqye()
}

const reqye = async () => {
  const result = await requserBalances({
    user_id: userId.value,
    page: djyPage.value
  })

  if (result.code === 200) {
    tableData.value = result.data.data
    ztsNum.value = result.data.total
    BlanaceDetail.value = true
  }
}

const showIPDialog = async (ip) => {
  if (!ip) return showToast({ type: 'fail', message: '未获取到最新IP' })
  showIP.value = true
  htmlStr.value = ''
  const result = await reqGetUserIPAddress(ip)
  if (result.code === 200) {
    const dataHtml = result.data
    const div = document.createElement('div')
    div.innerHTML = dataHtml
    document.head.appendChild(div)
    const table = document.querySelector('.table-box table')
    table.querySelector('tfoot').remove()
    htmlStr.value = table.innerHTML
    div.remove()
  } else {
    htmlStr.value = '获取失败'
  }
}

const editUser = async () => {
  showEdit.value = true
  userParams.value = {}
  const userId = currentUser.value.id
  const result = await reqGetUser(userId)
  if (result.code === 200) {
    console.log(result.data)
    userParams.value = result.data
  }
}

const changeAnchor = async (status) => {
  console.log(status);
  userParams.value.is_anchor = status ? 1 : 0
  const result = await reqEditUser(currentUser.value.id, userParams.value)
  if (result.code === 200) {
    onRefresh()
    showToast({ type: 'success', message: '修改成功' })
  } else {
    showToast({ type: 'fail', message: '修改失败' })
  }
}
</script>

<template>
  <div class="user-container">
    <form class="search-form">
      <van-search v-model="searchValue" show-action clearable placeholder="请输入用户id" @search="onSearch"
        clear-trigger="always">
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </form>

    <van-dropdown-menu>
      <van-dropdown-item @change="onRefresh" v-model="vipType" :options="typeList" />
    </van-dropdown-menu>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list class="user-list" v-model:loading="loading" :finished="page >= lastPage" finished-text="没有更多了"
        @load="onLoadMore">
        <UserItem @showDetail="showDetailDialog(user)" @click-control="showControl" @change-status="onChangeStatus" @zxChange="zxChange" @rechargeStatus="rechargeStatus"
          @blanaceDetail="onBlanaceDetail(user)" v-for="user in users" :key="user.id" :user="user" />
      </van-list>
      <van-back-top bottom="10vh" />
    </van-pull-refresh>

    <van-dialog v-model:show="isShowDialog" title="操作" show-cancel-button @confirm="onSubmit">
      <div class="dialog-content">
        <van-field label="用户ID" :model-value="currentUserId" readonly input-align="right" />
        <van-radio-group v-model="type">
          <van-cell-group>
            <van-cell title="充值" clickable @click="type = '0'">
              <template #right-icon>
                <van-radio name="0" />
              </template>
            </van-cell>
            <van-cell title="扣除" clickable @click="type = '1'">
              <template #right-icon>
                <van-radio name="1" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <van-cell title="类型" is-link :value="selectType" @click="showType = true" />
        <van-cell v-if="selectType === '优惠卷'" title="优惠卷" is-link :value="selectCoupon" @click="showCoupon = true" />
        <!-- 允许输入正整数，调起纯数字键盘 -->
        <van-field v-model="count" type="number" label="数量" placeholder="请输入数量" input-align="right" />
      </div>
    </van-dialog>
    <van-action-sheet v-model:show="showType" :actions="actions" @select="onSelect" close-on-click-action
      cancel-text="取消" />
    <van-action-sheet v-model:show="showCoupon" :actions="couponList" @select="(arg) => (selectCoupon = arg.name)"
      close-on-click-action cancel-text="取消" />
    <van-dialog v-model:show="showDetail" title="详情" show-cancel-button cancel-button-text="关闭" confirm-button-text="修改"
      @confirm="editUser">
      <van-cell-group style="max-height: 70vh; overflow-y: scroll">
        <van-cell center :title="currentUser.nickname" :label="currentUser.id">
          <template #value>
            <van-image radius="50%" :src="currentUser.avatar" fit="cover" width="30"></van-image>
          </template>
        </van-cell>
        <van-cell title="上级ID" :value="currentUser.parent_id === 0 ? '无' : currentUser.parent_id" />
        <van-cell title="手机号" :value="currentUser.mobile"></van-cell>
        <van-cell title="等级" :value="'vip' + currentUser.level_id"></van-cell>
        <van-cell title="平台" :value="currentUser.market"></van-cell>
        <van-cell title="金币" :value="currentUser.account.balance"> </van-cell>
        <van-cell title="钻石" :value="currentUser.account.point"> </van-cell>
        <van-cell title="水晶" :value="currentUser.account.crystal"> </van-cell>
        <van-cell title="总消费" :value="currentUser.account.total_pay"> </van-cell>
        <van-cell title="总充值" :value="currentUser.account.total_recharge"> </van-cell>
        <van-cell @click="showIPDialog(currentUser.last_login_ip)" title="最新IP"
          :value="currentUser.last_login_ip || '暂无'" is-link></van-cell>
        <van-cell title="注册时间" :value="currentUser.created_at"></van-cell>
        <van-cell title="更新时间" :value="currentUser.updated_at"></van-cell>
      </van-cell-group>
    </van-dialog>
    <van-dialog v-model:show="showIP" title="IP地址">
      <table v-html="htmlStr"></table>
    </van-dialog>
    <van-dialog v-model:show="showEdit" title="修改" show-cancel-button :show-confirm-button="false"
      cancel-button-text="关闭">
      <van-cell title="主播">
        <template #value>
          <van-switch :model-value="userParams.is_anchor === 1" @change="changeAnchor"></van-switch>
        </template>
      </van-cell>
    </van-dialog>

    <van-dialog v-model:show="BlanaceDetail" title="余额" show-cancel-button @confirm="celenlBlanace">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="jb_balance" label="金币余额" width="180" />
        <el-table-column prop="zs_balance" label="钻石余额" width="180" />
        <el-table-column prop="crystal" label="水晶" width="180" />
        <el-table-column prop="prize_total_balance" label="赏品总额" width="180" />
        <el-table-column prop="box_bag_balance" label="宝箱总额" width="180" />
        <el-table-column prop="take_order_balance" label="提货总额" width="180" />
        <el-table-column prop="prize_lock_balance" label="保险柜总额" width="180" />
        <el-table-column prop="total_balance" label="总余额" width="180" />
        <el-table-column prop="created_at" label="创建日期" width="180" />
      </el-table>
      <el-pagination :total="ztsNum" layout="prev, pager, next" :page-size="10" @change="paginationChage" />
    </van-dialog>
  </div>
</template>

<style scoped lang="less">
/deep/.van-dialog {
  width: 98% !important;
}

.user-container {
  .search-form {
    padding: 0 10px;
  }
}

.dialog-content {
  padding: 20px 0;
}
</style>
